package ernie.server;

import ernie.server.context.HelloWorldContext;
import ernie.server.context.MyStocksContext;
import ernie.server.context.MyNordnetDirektDepoContext;
import ernie.server.context.ThreadCommandContext;
import graph.autodrawer.AutoDrawer;

import java.io.File;
import java.net.InetSocketAddress;

import stock.avanza.AvanzaScrape;
import stock.netfonds.NetFondsParser;
import stock.nordnet.NordnetScrape;

import com.sun.net.httpserver.HttpServer;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 6:41:49 PM - Nov 11, 2011
 */
public class MyParseServer implements Runnable {
    private static final int PORT = 8080;
    
    private HttpServer server;
    
    private final AvanzaScrape avanza;
    private final AutoDrawer autoDrawer;
    private final NordnetScrape nordnet;
    private final NetFondsParser netfonds;

    public MyParseServer() {
        avanza = new AvanzaScrape();
        autoDrawer = new AutoDrawer(avanza);
        avanza.setAutoDrawer(autoDrawer);
        new Thread(avanza).start();
        nordnet = new NordnetScrape();
        new Thread(nordnet).start();
        netfonds = new NetFondsParser();
        new Thread(netfonds).start();

        tryCreateHttpServer();
        File pagesroot = new File(System.getProperty("user.dir"));
        pagesroot = new File(pagesroot, "/html");
        server.createContext("/setFast.php", new ThreadCommandContext(avanza));
        server.createContext("/", new HelloWorldContext());
        server.createContext("/myStocks.php", new MyStocksContext(autoDrawer));
        server.createContext("/myDepo.json", new MyNordnetDirektDepoContext());
        server.setExecutor(null); // creates a default executor

        System.out.println(avanza.getMyFollowedStockNames());
        new Thread(autoDrawer).start();
    }

    @Override
    public void run() {
        System.out.println("Server started on port " + PORT);
        server.start();
    }

    private void tryCreateHttpServer() {
        try {
            server = HttpServer.create(new InetSocketAddress(PORT), 6);
        } catch (Exception e) {
            System.out.println(
                    e.getMessage());
            System.out.println(
                    "Failed to create http server, retrying in 5 secs");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e2) {}
            tryCreateHttpServer();
        }
    }

    public static void main(String[] args) {
        new MyParseServer().run();
    }
}
